#import "BillsManager.h"
#import "Product.h"

@interface BillsManager ()

@end

static NSString* kBillUrl = @"http://78.90.20.186:8080/ProjectRestaurant/getBill?tableId=";
static NSString* kDeleteOrderUrl = @"http://78.90.20.186:8080/ProjectRestaurant/deleteOrder";

@implementation BillsManager

+(void) getBillForTable:(Table*) table{
    NSURLSession* session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
    
    NSURLRequest* request = [NSURLRequest requestWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@%ld", kBillUrl, (long)table.tableNumber]]];
    NSURLSessionDataTask* downloadJSONTask = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
        
        NSError* mistake = nil;
        NSDictionary* jsonDictionary = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:&mistake];

        if (mistake != nil) {
            NSLog(@"Error : %@", [mistake localizedDescription]);
        }
        else {
            NSDictionary* item = [jsonDictionary objectForKey:@"response"];
            Bill* bill = [[Bill alloc] init];
            if (![item isEqual:[NSNull null]]){
                bill.billId = [item[@"billId"] integerValue];
                bill.tableId = [table tableNumber];
                bill.isPaid = [item[@"isPaid"] boolValue];
                bill.totalBill = [item[@"totalBill"] floatValue];
                table.bill = bill;
                NSMutableArray* orders = [[NSMutableArray alloc] init];
                
                for (NSDictionary* order in item[@"orders"]){
                    [bill addOrderId:[order[@"orderId"] integerValue]];
                   
                    
                    NSDictionary* product = order[@"product"];
                    Product* myProduct = [[Product alloc] init];
                    myProduct.name = product[@"name"];
                    myProduct.price = [product[@"price"] floatValue];
                    myProduct.productId = [product[@"productId"] integerValue];
                    [orders addObject:myProduct];
                }
                [bill setOrdersWithArray:orders];
            }
        }
        
        
    }];
    [downloadJSONTask resume];
}


+(void) deleteOrder:(NSInteger) orderId {
    
    NSDictionary *dict = [[NSDictionary alloc] initWithObjectsAndKeys:[NSNumber numberWithInteger:orderId], @"orderId", nil];
    if ([NSJSONSerialization isValidJSONObject:dict]) {
        
        NSError *error = nil;
        NSData *result = [NSJSONSerialization dataWithJSONObject:dict options:NSJSONWritingPrettyPrinted error:&error];
        
        if (error == nil && result != nil) {
            NSData *response = [self jsonPostRequest:result];
            
            NSError* mistake = nil;
            NSDictionary* jsonDictionary = [NSJSONSerialization JSONObjectWithData:response options:NSJSONReadingMutableLeaves error:&mistake];
            NSString *responseString = jsonDictionary[@"response"];
            
            if (mistake != nil) {
                NSLog(@"Error : %@", [mistake localizedDescription]);
            }
            else {
                
            }
        }
    }
}

+(id) jsonPostRequest:(NSData*) jsonRequestData{
    NSURL *url = [NSURL URLWithString:kDeleteOrderUrl];
    
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:0 timeoutInterval:60];
    [request setHTTPMethod:@"POST"];
    [request setValue:@"application/json" forHTTPHeaderField:@"Accept"];
    [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
    [request setValue:[NSString stringWithFormat:@"%lu", (unsigned long)[jsonRequestData length]] forHTTPHeaderField:@"Content-Length"];
    [request setHTTPBody:jsonRequestData];
    
    //send synch request
    NSURLResponse *response = nil;
    NSError *error = nil;
    NSData *result = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
    
    
    if (error == nil) {
        return result;
    }
    else{
        return nil;
    }
}

@end
